<?php
session_start();
$strNames = $_GET['q'];
$arrNames = explode(',', $strNames);

$db_connect = mysqli_connect("localhost", "root", "", "tractors");

$user = $_SESSION['username'];
$query = "select money from user where username = '$user'";
				
$result = mysqli_query($db_connect, $query);

$row = mysqli_fetch_assoc($result);
$userMoney = $row['money'] + 0;

$query2 = "SELECT sum(price) as price FROM `tractor` WHERE ";
$temp = "";
foreach($arrNames as $v)
{
	$temp .= "`name` LIKE '$v'  or ";
}

$temp = substr($temp, 0, strlen($temp)-3);
$query2 .= $temp;

$result1 = mysqli_query($db_connect, $query2);

$row2 = mysqli_fetch_assoc($result1);

$neededMoney = $row2['price'] + 0;

if($userMoney >= $neededMoney)
{
	$query3 = "delete from tractor where " . $temp;	
	mysqli_query($db_connect, $query3);
	if(mysqli_affected_rows($db_connect) > 0)
	{
		$leftMoney = $userMoney - $neededMoney;
		$query4 = "UPDATE `user` SET `money` = '$leftMoney' WHERE name = '$user'";
		mysqli_query($db_connect, $query4);
		if(mysqli_affected_rows($db_connect) > 0)
		{
			echo "1";
		}
		else 
		{
			echo "-3";
		}
	}
	else {
		echo "-2";
	}
}
else 
{
	echo "-1";
}

mysqli_close($db_connect);

 
?>